package com.example;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import com.example.utils.JdbcUtils;

import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@WebServlet("/articleadd")
public class ArticleAdd extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        RequestDispatcher rp = req.getRequestDispatcher("/WEB-INF/jsp/articleAdd.jsp");
        rp.forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String title = req.getParameter("title");
        String author = req.getParameter("author");
        String content = req.getParameter("content");
        System.out.println("title=" + title+"\tauthor="+author+"\tcontent="+content);
        
        Connection conn = null;
        PreparedStatement ppst = null;
        
        // 插入数据
        try {
            conn = JdbcUtils.getConnection();
            String sql = "INSERT INTO article(title,author,content) VALUES(?,?,?)";
            ppst = conn.prepareStatement(sql);
            ppst.setString(1, title);
            ppst.setString(2, author);
            ppst.setString(3, content);
            
            int executeUpdate = ppst.executeUpdate();
            System.out.println("添加:"+ executeUpdate +"条记录.");
            JdbcUtils.release(conn, ppst);
            
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
